//
//  HomeTableViewController.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/3.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 微博原创 Cell 的可重用表示符号
let StatusNormalCellId = "StatusNormalCellId"
/// 微博转发Cell的可重用标示符
let StatusRetweetedCellId = "StatusRetweetedCellId"

class HomeTableViewController: VisitorTableViewController {
    ///微博数据数组
    private var listViewModel = StatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !UserAccountViewModel.sharedUserAccount.userLogon{
            visitorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            
            return
        }
        
        prepareTableView()
        
        loadData()
        //注册查看大图通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification, object: nil, queue: nil) {[weak self] (n) -> Void in
            
            guard let urls = n.userInfo![WBStatusSelectedPhotoURLKey] as? [NSURL] else {
                return
            }
            
            guard let indexPath = n.userInfo![WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                return
            }
            guard let cell = n.object as? PhotoBrowserPresentDelegate else {
                return
            }
            
            let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
            //设置modal模式,告诉控制器，modal要自定义
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            //设置转场动画代理,告诉控制器由谁实现动画
            vc.transitioningDelegate = self?.photoBrowserAnimator
            //设置转场动画参数
            self?.photoBrowserAnimator.setDelegateParams(cell, dismissDelegate: vc, indexPath: indexPath)
            
           self?.presentViewController(vc, animated: true, completion: nil)
            
        }
        
    }
    //注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    ///准备表格
    private func prepareTableView() {
        //注册可重用cell 
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusRetweetedCellId)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusNormalCellId)
        //取消分割线
        tableView.separatorStyle = .None
        
        //自动计算行高
        tableView.estimatedRowHeight = 400
        tableView.rowHeight = 400
//        tableView.rowHeight = UITableViewAutomaticDimension
        
        //下拉刷新视图
        refreshControl = WBRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        //上拉刷新视图
        tableView.tableFooterView = pullupView
        
    }
    ///加载数据
    @objc private func loadData() {
//        print("loaddata")
//       self.refreshControl?.beginRefreshing()
        listViewModel.loadData(isPullup: pullupView.isAnimating(), finished:{ (isSucceed) -> () in
            //加载完成后关闭下拉刷新
            self.refreshControl?.endRefreshing()
            //加载完成后关闭上拉刷新
            self.pullupView.stopAnimating()
            
            if !isSucceed {
                SVProgressHUD.showInfoWithStatus("数据加载错误，请稍后再试")
                return
            }
            self.showPulldownTip()
            
            self.tableView.reloadData()
        })
    }
    //显示下拉刷新标记
    var flag = false
    ///显示下拉刷新提示数据
    private func showPulldownTip() {
        guard let count = listViewModel.pulldownCount else {
            return
        }
        let message = count > 0 ? "刷新到了 \(count) 条微博" : "没有刷新到数据"
        let height: CGFloat = 30
        let rect = CGRectMake(0, (navigationController?.navigationBar.bounds.height)! - height, view.bounds.width, height)
        pulldownTipLabel.text = message
        pulldownTipLabel.frame = rect
        self.pulldownTipLabel.backgroundColor = UIColor.orangeColor()

        if !flag {
            
            UIView.animateWithDuration(1.0, animations: { () -> Void in
                self.pulldownTipLabel.frame = CGRectOffset(rect, 0, height)
                self.flag = true
                }) { (_) -> Void in
                    UIView.animateWithDuration(1.0, delay: 1.5, options: [], animations: { () -> Void in
                    self.pulldownTipLabel.frame = rect
                    }, completion: { (_) -> Void in
                        self.pulldownTipLabel.backgroundColor = UIColor.clearColor()
                        self.flag = false
                })

            }
        }
        
    }
    
    //MARK: - 懒加载数据
    //下拉提示标签
    private lazy var pulldownTipLabel: UILabel = {
        let label = UILabel(title: "", color: UIColor.whiteColor(), fontSize: 14)
//        label.backgroundColor = UIColor.orangeColor()
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
    
    //上拉刷新视图
    private lazy var pullupView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.lightGrayColor()
        return indicator
    }()
    //转场动画
    private lazy var photoBrowserAnimator: PhotoBrowserAnimator = PhotoBrowserAnimator()

    
}

//MARK: - 数据源方法
extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listViewModel.statusList.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let vm = listViewModel.statusList[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! StatusCell

        cell.viewModel = vm
        //判断是否需要上拉刷新数据
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
            print("上拉刷新数据")
            pullupView.startAnimating()
            loadData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return listViewModel.statusList[indexPath.row].rowHeight

    }
}











